<template>
    <img :data-id="image._id" v-lazy="image.baseInfo.src + '?thumb=true'" :style="imgStyle" :alt="image.baseInfo.name" />
    
</template>

<script type="text/javascript">
import Vue from 'vue'
import VueLazyload from 'vue-lazyload'
import smartMouse from "./smart-mouse"

Vue.use(VueLazyload, {
    preLoad: 1.3,
    error: '/static/error.png',
    loading: '/static/loading.svg',
    attempt: 1
});

export default {
    mixins: [smartMouse],
    name: 'thumb-img',
    props: {
        'size': {
            type: Number,
            required: true
        },
        'image': {
            type: Object,
            required: true
        }
    },
    data() {
        return {
            loaded: false,

        }
    },
    computed: {
        imgStyle() {
            var width, height, tx, ty;
            if (!this.loaded) {
                width = height = this.size * 0.8;
            } else {
                var rate = this.image.baseInfo.height / this.image.baseInfo.width;
                if (rate > 1) {
                    width = this.size;
                    height = width * rate;
                } else {
                    height = this.size;
                    width = height / rate;
                }
            }
            tx = (width - this.size) / 2;
            ty = (height - this.size) / 2;
            return {
                width: width + 'px',
                height: height + 'px',
                transform: `translate(${-tx}px, ${-ty}px)`
            }
                
        }
    },
    created() {
        var vm = this;
        var handler = function({el}) {
            if (el == vm.$el) {
                vm.$Lazyload.$off('loaded', handler);
                vm.loaded = true;
                // console.log('loaded', vm.$el);
            }
            
            
        };
        vm.$Lazyload.$on('loaded', handler);
    }
}

</script>

<style type="text/css" scoped>
    
</style>